﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using client.AlertsService;
using client.Settings;
using client.Managers.Registration;

namespace client.Managers.Connection
{
    public class Publisher
    {
        private static readonly Publisher instance = new Publisher();
        private readonly object locker = new object();
        private readonly List<AlertsListener> listeners = new List<AlertsListener>();
        private Timer timer;
        private Publisher()
        {
            this.timer = new Timer(
            this.DoWork,
            new object(),
            0,
            UserSettings.timeDelay*6000);
        }
        public delegate void AlertsListener(object sender, AlertsPublisherEventArgs args);
        public void AddListener(AlertsListener del)
        {
            //SomeDelegate test;
            this.listeners.Add(del);
        }

        /// <summary>
        /// Removes listener from list
        /// </summary>
        /// <param name="del">Delegate to be removed from the list of listeners.</param>
        public void RemoveListener(AlertsListener del)
        {
            this.listeners.Remove(del);
        }

        /// <summary>
        /// Do some work, update state for example
        /// </summary>
        /// <param name="state"></param>
        public void DoWork(object state)
        {
            lock (this.locker)
            {
                //Checking internet state, and register options
                if (!ConnectionManager.IsConnected()||
                    !RegistrationManager.IsApplicationRegistered())
                {
                    return;
                }
                
                //Receiving alerts from server
                List<BaseAlert> alerts = AlertServiceManager.LookForAlerts(UserSettings.UserName);
                
                //Notifing all listeners
                foreach (AlertsListener currentDelegate in listeners)
                {
                    currentDelegate(this, new AlertsPublisherEventArgs(alerts));
                }
            }
        }
        /// <summary>
        /// Returns instance of publisher object
        /// </summary>
        public static Publisher Instance
        {
            get { return instance; }
        }
    }
}
            
